package com.jx.lcs.productbill.service;

import java.net.URLDecoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jx.lcs.integral.entity.IntegralActivity;
import com.jx.lcs.integral.entity.UserIntegral;
import com.jx.lcs.integral.service.IntegralActivityService;
import com.jx.lcs.integral.service.IntegralTypeService;
import com.jx.lcs.integral.service.UserIntegralService;
import com.jx.lcs.product.entity.ProductInfo;
import com.jx.lcs.productbill.dao.ProductBillDao;
import com.jx.lcs.productbill.entity.ProductBill;
import com.jx.lcs.productorder.dao.ProductOrderDao;
import com.jx.lcs.productorder.entity.ProductOrder;
import com.tianyu.jty.common.persistence.HibernateDao;
import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.service.BaseService;
import com.tianyu.jty.common.utils.DateUtils;

/** 
 * 
 * @author JiaYY 
 * @date 2015年7月15日
 */

@Service
@Transactional(readOnly=true)
public class ProductBillService extends BaseService<ProductBill, String> {

	@Autowired
	private ProductBillDao productBillDao;
	
	@Autowired
	private ProductOrderDao productOrderDao;
	
	@Autowired
	private UserIntegralService userIntegralService;
	
	@Autowired
	private IntegralTypeService integralTypeService;
	
	@Autowired
	private IntegralActivityService integralActivityService;
	
	@Override
	public HibernateDao<ProductBill, String> getEntityDao() {
		return productBillDao;
	}
	
	public Page<ProductBill> findProductBillList(Page<ProductBill> page, HttpServletRequest request) throws Exception {
		String orderId = request.getParameter("orderId");
		String pname = request.getParameter("pname");
		String pcode = request.getParameter("pcode");
		String userName = request.getParameter("userName");
		String uid = request.getParameter("uid");
		String cname = request.getParameter("cname");
		String cid = request.getParameter("cid");
		String status = request.getParameter("status");
		String beginDate = request.getParameter("beginDate");
		String endDate = request.getParameter("endDate");
		
		StringBuilder sb = new StringBuilder();
		sb.append("from ProductBill t where t.productOrder.id != null and t.productOrder.user.id != null and t.productOrder.productInfo.id != null");
		
		if(orderId != null && !"".equals(orderId.trim())) {
			sb.append(" and t.productOrder.id = '").append(orderId).append("'");
		}
		if(pname != null && !"".equals(pname.trim())) {
			pname = URLDecoder.decode(pname, "UTF-8");
			sb.append(" and t.productOrder.productInfo.pname like '%").append(pname).append("%'");
		}
		if(pcode != null && !"".equals(pcode.trim())) {
			sb.append(" and t.productOrder.productInfo.pcode like '%").append(pcode).append("%'");
		}
		if(userName != null && !"".equals(userName.trim())) {
			userName = URLDecoder.decode(userName, "UTF-8");
			sb.append(" and t.productOrder.user.userName like '%").append(userName).append("%'");
		}
		if(uid != null && !"".equals(uid.trim())) {
			sb.append(" and t.productOrder.user.uid like '%").append(uid).append("%'");
		}
		if(cname != null && !"".equals(cname.trim())) {
			cname = URLDecoder.decode(cname, "UTF-8");
			sb.append(" and t.productOrder.cname like '%").append(cname).append("%'");
		}
		if(cid != null && !"".equals(cid.trim())) {
			sb.append(" and t.productOrder.cid like '%").append(cid).append("%'");
		}
		if(status != null && !"".equals(status.trim())) {
			sb.append(" and t.status = '").append(status).append("'");
		}
		if(beginDate != null && !"".equals(beginDate.trim())) {
			sb.append(" and t.productOrder.orderTime > '").append(beginDate).append("'");
		}
		if(endDate != null && !"".equals(endDate.trim())) {
			sb.append(" and t.productOrder.orderTime <= '").append(endDate).append(" 23:59:59'");
		}
		sb.append(" and t.productOrder.id != null and t.productOrder.status != '' order by t.createTime desc");
		
		return productBillDao.findPage(page, sb.toString(), new Object[]{});
	}
	
	/**
	 * 关单审核
	 * @param id
	 * @param status
	 * @return
	 */
	@Transactional(readOnly = false)
	public String examCard(String id, String status) throws Exception {
		String result = null;
		
		ProductBill bill = productBillDao.find(id);
		ProductOrder order = bill.getProductOrder();
		
		if(bill != null && bill.getId() != null) {
			bill.setStatus(status);
			productBillDao.save(bill);
			
			if("2".equals(status)) {
				if(order != null && order.getId() != null) {
					order.setStatus("0");
					Date date = DateUtils.getSysDate();
					order.setOrderTime(date);
					if("1".equals(order.getSource())){//如果是C端预约，需要同时更新确认时间
						order.setConfirmTime(date);
					}
					productOrderDao.save(order);
				}
				
				return result;
			}
		} else {
			result = "该关单不存在！";
			
			return result;
		}
		
		// 审核通过后给理财师增加积分
		// 获取预约详细信息
		ProductInfo product = order.getProductInfo();
		String uid = order.getUser().getUid();		// 获得理财师ID

		// 积分计算
		UserIntegral userIntegral = null;
		String title="";
		
		//获取积分活动
		IntegralActivity activity = integralActivityService.getIntegralActivity();
		long currTime = DateUtils.getSysDate().getTime();
		boolean activityAble = false;
		if(activity != null && currTime >= activity.getBeginTime().getTime() && currTime <= activity.getEndTime().getTime()) {
			activityAble = true;
		}
			
		//查找是否一个给该理财师增加过代理该产品积分
		int rtn = integralTypeService.isHaveAgentIntegral(uid, product.getPcode());
		if(rtn == 0){
			int agentScore = integralTypeService.findIntegralTypeByTypeName(
				"PRODUCT_AGENT").getScore();// 代理积分类型	
			if(activityAble) agentScore *= activity.getMultiple();
			
			userIntegral = new UserIntegral();
			userIntegral.setUid(uid);
			userIntegral.setIncomeType("0");
			userIntegral.setRecordTime(new Date());
			userIntegral.setScore(agentScore);
			userIntegral.setSource("1");
			userIntegral.setSourceCode(product.getPcode());			
			title = "成功代理产品\"" + product.getPname() + "\"";
			userIntegral.setTitle(title);			
			userIntegralService.save(userIntegral);
		}
		
		int orderScore = integralTypeService.findIntegralTypeByTypeName(
				"PRODUCT_ORDER").getScore();// 预约积分
		orderScore = (int) (orderScore * (order.getInvestMoney().longValue() / 100000));
		if(activityAble) orderScore *= activity.getMultiple();
		
		userIntegral = new UserIntegral();
		userIntegral.setUid(uid);
		userIntegral.setIncomeType("0");
		userIntegral.setRecordTime(new Date());
		userIntegral.setScore(orderScore);
		userIntegral.setSource("2");
		userIntegral.setSourceCode(product.getPcode());
		title = "成功预约客户（" + order.getCname() + "）";
		userIntegral.setTitle(title);
		userIntegralService.save(userIntegral);

		int billScore = integralTypeService.findIntegralTypeByTypeName(
				"PRODUCT_BILL").getScore();// 关单积分
		billScore = (int) (billScore * (order.getInvestMoney().longValue() / 100000));
		if(activityAble) billScore *= activity.getMultiple();
		
		userIntegral = new UserIntegral();
		userIntegral.setUid(uid);
		userIntegral.setIncomeType("0");
		userIntegral.setRecordTime(new Date());
		userIntegral.setScore(billScore);
		userIntegral.setSource("3");
		userIntegral.setSourceCode(product.getPcode());
		title = "客户（" + order.getCname() + "）成功进入关单";
		userIntegral.setTitle(title);
		userIntegralService.save(userIntegral);
		
		return result;
	}
	
}
